package tcp

import (
	"context"
	"fmt"
	"net"
	"os"
	"os/signal"
	"sync"
	"syscall"
)

func ListenAndServerWithSignal(handle Handler) error {
	closeChan := make(chan struct{})
	listen, err := net.Listen("tcp", ":9999")
	if err != nil {
		return err
	}
	signChan := make(chan os.Signal)
	signal.Notify(signChan, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGHUP)
	go func() {
		s := <-signChan
		switch s {
		case syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGHUP:
			closeChan <- struct{}{}
		}
	}()
	fmt.Println("启动监听")
	ListenAndServe(listen, handle, closeChan)
	return nil
}
func ListenAndServe(listener net.Listener, handler Handler, closeChan <-chan struct{}) {
	go func() {
		<-closeChan
		fmt.Println("shutting down")
		err3 := listener.Close()
		fmt.Println(err3)
		err3 = handler.Close()
		fmt.Println(err3)
	}()
	defer func() {
		err2 := listener.Close()
		fmt.Println(err2)
		err := handler.Close()
		fmt.Println(err)
	}()
	var waitGroup sync.WaitGroup
	for true {
		accept, err := listener.Accept()
		waitGroup.Add(1)
		if err != nil {
			break
		}
		go func() {
			defer waitGroup.Done()
			handler.Handle(context.Background(), accept)
		}()
	}
	waitGroup.Wait()
}
